package com.swotxu.mall.product.exception;

import com.swotxu.common.exception.BizCodeEnum;
import com.swotxu.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Map;
import java.util.stream.Collectors;

/**
 * 统一异常处理
 *
 * @Date: 2020/12/26 19:03
 * @Author: swotXu
 */
@Slf4j
//@ResponseBody
//@ControllerAdvice()
@RestControllerAdvice(basePackages = "com.swotxu.mall.product.controller")
public class MallExceptionControllerAdvice {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleVaildException(MethodArgumentNotValidException e) {
        log.warn(BizCodeEnum.VALID_EXCEPTION.getMessage(), e);

        BindingResult bindingResult = e.getBindingResult();
        Map<String, String> map = bindingResult.getFieldErrors().stream()
                .collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
        return R.error(BizCodeEnum.VALID_EXCEPTION).setData(map);
    }

    @ExceptionHandler(value = Throwable.class)
    public R handleException(Throwable throwable) {
        log.warn(BizCodeEnum.UNKNOW_EXCEPTION.getMessage(), throwable);

        return R.error(BizCodeEnum.UNKNOW_EXCEPTION);
    }

}
